package com.wd.mylibrary_base.socket;

import android.content.Context;
import android.text.TextUtils;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Response;
import okio.ByteString;

public class WebSocketUtils {
    public interface OnMessageListener {
        void message(String msg);
    }

    private OnMessageListener mOnMessageListener;

    public void setOnMessageListener(OnMessageListener mOnMessageListener) {
        this.mOnMessageListener = mOnMessageListener;
    }

    private WsManager mWsManager;
    private int mNumber = 0;
    private WsStatusListener mWsStatusListener = new WsStatusListener() {
        @Override
        public void onOpen(Response response) {
            super.onOpen(response);
        }

        @Override
        public void onMessage(String text) {
            super.onMessage(text);
            mOnMessageListener.message(text);
        }

        @Override
        public void onMessage(ByteString bytes) {
            super.onMessage(bytes);
        }

        @Override
        public void onReconnect() {
            super.onReconnect();
        }

        @Override
        public void onClosing(int code, String reason) {
            super.onClosing(code, reason);
        }

        @Override
        public void onClosed(int code, String reason) {
            super.onClosed(code, reason);
        }

        @Override
        public void onFailure(Throwable t, Response response) {
            super.onFailure(t, response);
        }
    };

    public WebSocketUtils startConnect(String url, Context context) {
        if (!TextUtils.isEmpty(url) && url.contains("ws")) {
            if (mWsManager != null) {
                mWsManager.stopConnect();
                mWsManager = null;
            }
            mWsManager = new WsManager.Builder(context)
                    .client(
                            new OkHttpClient().newBuilder()
                                    .pingInterval(15, TimeUnit.SECONDS)
                                    .retryOnConnectionFailure(true)
                                    .build())
                    .needReconnect(true)
                    .setReconnnectInterval(3 * 1000)  //设置重连步长(ms)
                    .setReconnnectIMaxTime(120 * 1000) //设置重连最大时长
                    .wsUrl(url)
                    .build();
            mWsManager.setWsStatusListener(mWsStatusListener);
            mWsManager.startConnect();
        }
        return this;
    }


    public void closeConnect() {
        if (mWsManager != null) {
            mWsManager.stopConnect();
            mWsManager = null;
        }
    }
}
